<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 -->
<!-- 
* @desc:服务节点编辑弹出框组件
* @fileName:service-editor.vue
* @author:zhouyongjie@yzbdl.ac.cn
* @date:2022-4-6
!-->

<script setup lang="ts">
import Load from "@/components/common/load.vue";
import { onMounted, reactive, ref } from "vue";
import { FormInstance } from "element-plus";

import { getCurrentInstance } from "vue";
import { isPort } from "@/common/util/is-port";
import { showErrorMessage, showSuccessMessage } from "@/common/message";
const { proxy } = getCurrentInstance() as any;
//接收父组件传值
const props = defineProps({
  handleEditFunc: Function as any,
  editItem: Object as any,
});
//定义参数
const ruleForm = reactive({
  programName: "",
  serverName: "",
  programPort: "",
  userName: "",
  password: "",
  serverIp: "",
  category: "",
  id: "",
  remark: "",
  status: "" as any,
  serverId: "",
});
let changeStatus = props.editItem.status;
const formSize = ref("default");
const showLoad = ref(false);
const ruleFormRef = ref<FormInstance>();
const labelPosition = ref("top");
let options = reactive({
  List: [] as any,
});

/**
 * @description: 验证端口号
 * @param {any} rule
 * @param {any} value
 * @param {any} callback
 * @return void
 */
const validatePort = (rule: any, value: any, callback: any) => {
  if (!isPort(value)) {
    callback(new Error("端口号不符合规则"));
  } else {
    callback();
  }
};
const clickConncet = ref(false);
//定义校验规则
const rules = reactive({
  programName: [
    { required: true, message: "请输入服务节点名称", trigger: "blur" },
    { min: 1, max: 64, message: "长度为1-64位", trigger: "blur" },
  ],
  programPort: [
    { required: true, message: "请输入主机端口", trigger: "blur" },
    { validator: validatePort, trigger: "blur" },
  ],
  serverName: [{ required: true, message: "请选择对应主机", trigger: "blur" }],
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入用户密码", trigger: "blur" }],
});

/**
 * @description:获取服务ID
 * @return void
 */
const getServiceID = () => {
  const res = proxy.$HTTP.post({
    url: `/resource/server/query`,
    params: {
      page: 1,
      size: 1000,
    },
    data: {
      serverName: "",
      status: 1,
    },
  });
  res.then((res: any) => {
    if (res.isOk) {
      options.List = res.data.records;
    }
  });
  res.catch((error: any) => {
    if (error.data instanceof Array) {
      showErrorMessage({
        message: error.data[0].errorMsg,
      });
    } else {
      showErrorMessage({
        message: error.data,
      });
    }
  });
};
//提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (clickConncet.value === false) {
        showLoad.value = true;
        const res = proxy.$HTTP.post({
          url: `/resource/serverProgram/testConnection`,
          data: {
            userName: ruleForm.userName,
            password: ruleForm.password,
            serverIp: ruleForm.serverIp,
            serverId: ruleForm.serverId,
            programPort: ruleForm.programPort,
          },
        });
        res.then((res: any) => {
          showLoad.value = false;
          if (res.isOk) {
            if (res.data === 1) {
              changeStatus = 1;
              showSuccessMessage({
                message: "服务节点连接成功！",
              });
            }
            if (res.data === 0) {
              changeStatus = 0;
              showErrorMessage({
                message: "服务节点连接失败！",
              });
            }
            if (res.data === 2) {
              changeStatus = 2;
              showErrorMessage({
                message: "服务节点连接异常！",
              });
            }
            const submitres = proxy.$HTTP.put({
              url: `/resource/serverProgram`,
              data: {
                category: ruleForm.category,
                id: ruleForm.id,
                programName: ruleForm.programName,
                remark: ruleForm.remark,
                password: ruleForm.password,
                userName: ruleForm.userName,
                serverName: ruleForm.serverName,
                serverIp: ruleForm.serverIp,
                programPort: ruleForm.programPort,
                serverId: ruleForm.serverId,
                status: changeStatus,
              },
            });
            submitres.then((res: any) => {
              if (res.isOk) {
                console.log("res", res);
                props.handleEditFunc(valid);
              }
            });
            submitres.catch((error: any) => {
              if (error.data instanceof Array) {
                showErrorMessage({
                  message: error.data[0].errorMsg,
                });
              } else {
                showErrorMessage({
                  message: error.data,
                });
              }
            });
          }
        });
        res.catch((error: any) => {
          showLoad.value = false;
          if (error.data instanceof Array) {
            showErrorMessage({
              message: error.data[0].errorMsg,
            });
          } else {
            showErrorMessage({
              message: error.data,
            });
          }
        });
      } else {
        const submitres = proxy.$HTTP.put({
          url: `/resource/serverProgram`,
          data: {
            category: ruleForm.category,
            id: ruleForm.id,
            programName: ruleForm.programName,
            remark: ruleForm.remark,
            password: ruleForm.password,
            userName: ruleForm.userName,
            serverName: ruleForm.serverName,
            serverIp: ruleForm.serverIp,
            programPort: ruleForm.programPort,
            serverId: ruleForm.serverId,
            status: changeStatus,
          },
        });
        submitres.then((res: any) => {
          if (res.isOk) {
            console.log("res", res);
            props.handleEditFunc(valid);
          }
        });
        submitres.catch((error: any) => {
          if (error.data instanceof Array) {
            showErrorMessage({
              message: error.data[0].errorMsg,
            });
          } else {
            showErrorMessage({
              message: error.data,
            });
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
//连接测试
const connect = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      showLoad.value = true;
      const res = proxy.$HTTP.post({
        url: `/resource/serverProgram/testConnection`,
        data: {
          userName: ruleForm.userName,
          password: ruleForm.password,
          serverIp: ruleForm.serverIp,
          serverId: ruleForm.serverId,
          programPort: ruleForm.programPort,
        },
      });
      res.then((res: any) => {
        showLoad.value = false;
        if (res.isOk) {
          clickConncet.value = true;
          if (res.data === 1) {
            changeStatus = 1;
            showSuccessMessage({
              message: "服务节点连接成功！",
            });
          }
          if (res.data === 0) {
            changeStatus = 0;
            showErrorMessage({
              message: "服务节点连接失败！",
            });
          }
          if (res.data === 2) {
            changeStatus = 2;
            showErrorMessage({
              message: "服务节点连接异常！",
            });
          }
        }
      });
      res.catch((error: any) => {
        showLoad.value = false;
        if (error.data instanceof Array) {
          showErrorMessage({
            message: error.data[0].errorMsg,
          });
        } else {
          showErrorMessage({
            message: error.data,
          });
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const changeSelect = (val: any) => {
  options.List.map((item: any) => {
    if (item.serverName === val) {
      ruleForm.serverIp = item.serverIp;
      ruleForm.serverId = item.id;
      ruleForm.serverName = item.serverName;
      console.log("changeSelect", item);
    }
  });
};
//获取主机
onMounted(() => {
  getServiceID();
  let userInfo = { ...props.editItem };
  if (JSON.stringify(props.editItem) !== "{}") {
    ruleForm.id = userInfo.id;
    ruleForm.category = userInfo.category;
    ruleForm.programName = userInfo.programName;
    ruleForm.serverName = userInfo.serverName;
    ruleForm.programPort = userInfo.programPort;
    ruleForm.userName = userInfo.userName;
    ruleForm.password = userInfo.password;
    ruleForm.serverIp = userInfo.serverIp;
    ruleForm.serverId = userInfo.serverId;
    ruleForm.remark = userInfo.remark;
  }
});
</script>

<template>
  <Load v-if="showLoad" />
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :label-position="labelPosition"
    label-width="120px"
    :rules="rules"
    class="demo-ruleForm"
    :size="formSize"
  >
    <el-form-item label="服务节点名称" prop="programName">
      <el-input
        v-model="ruleForm.programName"
        size="large"
        placeholder="请输入服务节点名称"
      />
    </el-form-item>
    <el-form-item label="服务节点所在主机" prop="serverName">
      <el-select
        size="large"
        v-model="ruleForm.serverName"
        @change="changeSelect"
        style="width: 700px"
        clearable
        placeholder="请选择主机"
      >
        <el-option
          v-for="item in options.List"
          :key="item.serverName"
          :label="item.serverName"
          :value="item.serverName"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="主机端口" prop="programPort">
      <el-input
        v-model="ruleForm.programPort"
        size="large"
        placeholder="请输入主机端口"
      />
    </el-form-item>
    <el-form-item label="用户名" prop="userName">
      <el-input
        v-model="ruleForm.userName"
        size="large"
        placeholder="请输入用户名"
      />
    </el-form-item>
    <el-form-item label="用户密码" prop="password">
      <el-input
        v-model="ruleForm.password"
        size="large"
        type="password"
        show-password
        placeholder="请输入用户密码"
      />
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input
        v-model="ruleForm.remark"
        type="textarea"
        size="large"
        show-word-limit
        maxlength="512"
        placeholder="请输入备注"
      />
    </el-form-item>
    <el-form-item class="ClickButton">
      <el-button @click="connect(ruleFormRef)">连接测试</el-button>
      <el-button @click="submitForm(ruleFormRef)">确定</el-button>
    </el-form-item>
  </el-form>
</template>
<style lang="scss" scoped>
:deep(.el-form-item__label) {
  font-family: PingFang SC;
  font-weight: 700;
  color: #000000;
  font-size: 14px;
}
:deep(.el-input) {
  height: 40px;
  background-color: #ffffff;
}
:deep(.el-textarea) {
  height: 100px;
  background-color: #ffffff;
  .el-textarea__inner {
    height: 100px;
  }
}
.ClickButton {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: flex-end;

    .el-button {
      height: 40px;
      background-color: #ffffff;
      border: 1px solid;
      border-color: #cccccc;
    }
  }
}
</style>
